// user.js
const app = getApp()

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    userData: null,
    loading: false
  },
  onLoad() {
    this.getUserInfo()
  },
  onShow() {
    this.getUserInfo()
  },
  getUserInfo() {
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.setData({
        userInfo: userInfo,
        hasUserInfo: true
      })
      this.getUserData()
    }
  },
  getUserData() {
    const token = wx.getStorageSync('token')
    if (!token) {
      return
    }

    this.setData({ loading: true })
    
    wx.request({
      url: `${app.globalData.baseUrl}/user/profile`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({
            userData: res.data.data
          })
        } else {
          wx.showToast({
            title: res.data.message || '获取用户信息失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('获取用户信息失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      },
      complete: () => {
        this.setData({ loading: false })
      }
    })
  },
  login() {
    wx.login({
      success: (res) => {
        if (res.code) {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          wx.request({
            url: `${app.globalData.baseUrl}/miniprogram/login`,
            method: 'POST',
            data: {
              code: res.code
            },
            success: (loginRes) => {
              if (loginRes.data.code === 200) {
                const { token, userInfo } = loginRes.data.data
                wx.setStorageSync('token', token)
                wx.setStorageSync('userInfo', userInfo)
                this.setData({
                  userInfo: userInfo,
                  hasUserInfo: true
                })
                this.getUserData()
                wx.showToast({
                  title: '登录成功',
                  icon: 'success'
                })
              } else {
                wx.showToast({
                  title: loginRes.data.message || '登录失败',
                  icon: 'none'
                })
              }
            },
            fail: (err) => {
              console.error('登录失败:', err)
              wx.showToast({
                title: '登录失败',
                icon: 'none'
              })
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },
  logout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('token')
          wx.removeStorageSync('userInfo')
          this.setData({
            userInfo: {},
            hasUserInfo: false,
            userData: null
          })
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          })
        }
      }
    })
  },
  updateUserInfo() {
    wx.navigateTo({
      url: '../login/login'
    })
  }
})
